// socket功能
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import store from "./store";
import {getToken, getUser} from "@/utils/auth";
import {Message, Notification} from "element-ui";
import state from "@/store/state";

let sockJS = null
let stompClient = null
let username = null
let userId = null
let userProfile = null

export function socketConnect() {
    // 连接socketjs的endpoint
    // sockJS = new SockJS('http://192.168.1.56:8650/ws/chatroom');
    sockJS = new SockJS('http://localhost:8650/ws/chatroom');

    // 获取STOMP子协议的客户端对象
    stompClient = Stomp.over(sockJS);

    let header = {
        'Authorization' : getToken()
    }

    stompClient.connect(header, onConnected, onError)

    // 关闭控制台打印
    stompClient.debug = null

    username = JSON.parse(getUser()).username;
    userId = JSON.parse(getUser()).userId
    userProfile = JSON.parse(getUser()).userProfile

}

// 向服务器发起websocket连接
function onConnected() {
    console.log('连接成功')

    stompClient.subscribe('/user/topic/touser', this.onMessageReceived);

    stompClient.subscribe('/topic/chatroom', this.onMessageReceived);

    stompClient.subscribe('/chatroom/sendtotest', this.onMessageReceived);

    stompClient.subscribe('/chatroom/sendMessageTest', this.onMessageReceived);

    stompClient.subscribe('/chatroom/sendMsgGroup', this.onMessageReceived);

    //接收频率
    stompClient.heartbeat.incoming = 0
    //发送频率
    stompClient.heartbeat.outgoing  = 0

    stompClient.send('/chatroom/addUser', {},
        JSON.stringify({
            fromId: userId,
            fromName: username,
            from_profile: userProfile,
            toId: '-1',
            toName: 'all',
            messageTypeId: '1',
            createTime: new Date()
        })
    );
    Message({
        message: '欢迎来到LucienIM',
        type: 'success',
        duration: 2 * 1000
    })
    state.socketStatus = true
}

/**
 * 用户之间发送消息
 * @param content 消息内容
 * @param params
 *  {
 *      friend_id: '',      好友ID
        friendName: '',     好友昵称
 *  }
 */
export function sendMessage(content, params) {
    console.log('发送消息', stompClient)
    if(content && stompClient) {
        var chatMessage = {
            fromId: userId,
            fromName: username,
            fromProfile: userProfile,
            toId: params.friend_id,
            toName: params.friendName,
            messageTypeId: '2',
            content: content,
            createTime: new Date()
        };
        stompClient.send("/chatroom/sendMessageTest", {}, JSON.stringify(chatMessage));
    }
    return chatMessage;
}

/**
 * 发送群聊信息
 */
export function sendGroupMsg(params) {
    console.log('发送群聊信息')
    if (stompClient){
        var groupMsg = {
            groupId: params.groupId,
            userId: params.userId,
            username: params.username,
            userProfile: params.userProfile,
            content: params.content,
            messageTypeId: params.messageTypeId,
            createTime: new Date(),
        };
        stompClient.send("/chatroom/sendMsgGroup", {}, JSON.stringify(groupMsg));
    }
}

// 消息回调
export function onMessageReceived(payload) {
    var message = JSON.parse(payload.body);
    console.log('消息回调',message)
    if(message.messageTypeId === 1) {
        console.log(message.fromName + ' 上线~!');
    } else if (message.messageTypeId === 3) {
        console.log(message.fromName + ' 离线了!');
    } else {
        console.log('websocket接受消息')
    }
}

// 连接错误
export function onError(error) {
    Notification.error({
        title: 'websocket错误',
        message: '正在重连...'
    })
    this.socketConnect()
    console.log(error)
}

export function disConnect(){
    stompClient.disconnect()
}
